package routers

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"ztool/common"
	"ztool/dao"
)

/**
查询所有视频点位
*/
func getVideoDeviceList(c *gin.Context) {
	list, err := dao.QueryAllVideoDevice()
	if err != nil {
		c.JSON(http.StatusOK, common.RespError("查询失败"))
		return
	}

	r := common.RespData(list)
	c.JSON(http.StatusOK, r)
}

/**
分页查询
*/
func getVideoDevicePages(c *gin.Context) {

	//post参数中传递
	currentPage, err := strconv.ParseInt(c.PostForm("currentPage"), 10, 32)

	//标签
	tags := c.PostFormArray("tags")
	//名称
	name := c.PostForm("name")

	if err != nil {
		log.Println(err.Error())
		c.JSON(http.StatusOK, common.RespError("参数错误"))
		return
	}

	pages := dao.QueryVideoDevicePage(int32(currentPage), name, tags)
	pages.Code = 0
	c.JSON(http.StatusOK, pages)
}

//getVideoTags 获取视频标签
func getVideoTags(c *gin.Context) {
	id := c.Param("id")

	if id == "" {
		c.JSON(http.StatusOK, common.RespError("参数错误"))
		return
	}

	tags, err := dao.QueryVideoTags(id)

	if err != nil {
		c.JSON(http.StatusOK, common.RespError("获取标签失败"))
		return
	}

	c.JSON(http.StatusOK, common.RespData(tags))
}

/** addVideoDevice 添加设备 */
func addVideoDevice(c *gin.Context) {
	var device = dao.VideoDevice{}

	err := c.Bind(&device)

	if err == nil {
		if error := dao.AddVideoDevice(&device); error != nil {
			c.JSON(http.StatusOK, common.RespError("添加失败,错误"))
			return
		}

		c.JSON(http.StatusOK, common.RespSuccess("添加成功"))
		return
	}

	c.JSON(http.StatusOK, common.RespError("添加失败,错误："+err.Error()))
}

/** updateVideoDevice 编辑设备 */
func updateVideoDevice(c *gin.Context) {
	var device = dao.VideoDevice{}

	if c.ShouldBind(&device) == nil {
		dao.UpdateVideoDevice(&device)
		c.JSON(http.StatusOK, common.RespSuccess("修改成功"))
		return
	}

	c.JSON(http.StatusOK, common.RespError("修改失败"))
}

/** delVideoDevice 删除设备 */
func delVideoDevice(c *gin.Context) {
	id := c.Param("id")

	if id == "" {
		c.JSON(http.StatusOK, common.RespError("参数错误"))
		return
	}
	if err := dao.DeleteVideoDevice(id); err != nil {
		c.JSON(http.StatusOK, common.RespError("删除失败"))
		return
	}
	c.JSON(http.StatusOK, common.RespSuccess("删除成功"))
}

// loadVideoRouter 将路由组注册进去
func loadVideoRouter(e *gin.Engine) {
	//视频点位管理
	videoDevice := e.Group("/device")
	{
		//查询所有
		videoDevice.Any("/page", getVideoDevicePages)
		videoDevice.Any("/getList", getVideoDeviceList)
		videoDevice.POST("/getTags/:id", getVideoTags)
		videoDevice.POST("/add", addVideoDevice)
		videoDevice.POST("/update", updateVideoDevice)
		videoDevice.POST("/delete/:id", delVideoDevice)

	}
}
